<template>
    <a-spin :spinning="loading">
        <a-card :body-style="{paddingTop: '8px'}">
            <a-tabs @change="search" v-model="isHandle">
                <a-tab-pane :key="false" tab="待处理"></a-tab-pane>
                <a-tab-pane :key="undefined" tab="全部"></a-tab-pane>
                <a-tab-pane :key="true" tab="已处理"></a-tab-pane>
            </a-tabs>
            <a-row :gutter="16">
                <a-col class="mb-16 flex items-center" :span="6">
                    <span class="label">审核单号：</span>
                    <a-input v-model="auditRecordId" :max-length="100" @keyup.enter="search" class="flex-1"
                             placeholder="请输入审核单号"/>
                </a-col>
                <a-col class="mb-16 flex items-center" :span="6">
                    <span class="label">车牌号：</span>
                    <a-input v-model="vehicleLicenceNum" :max-length="50" @keyup.enter="search" class="flex-1"
                             placeholder="请输入车牌号"></a-input>
                </a-col>
                <a-col class="mb-16 flex items-center" :span="6">
                    <span class="label">服务商名称：</span>
                    <a-input v-model="vendorName" :max-length="50" @keyup.enter="search" class="flex-1"
                             placeholder="请输入服务商名称"></a-input>
                </a-col>
                <a-col :span="6">
                    <a-button type="primary" @click="search">查询</a-button>
                    <a-button class="mx-8" @click="reset">重置</a-button>
                </a-col>
            </a-row>
            <a-table :scroll="{x: 1200}" :columns="columns" class="table-con" :data-source="data"
                     :pagination="pagination">
                <template #id="id, data">
                    <section>{{ id }}</section>
                    <section>{{ $utils.getEnumName(auditEntityTypeEnums, data.auditEntityType) }}</section>
                </template>
                <template #userInfo="val, data">
                    <section class="mb-4">{{ data.vendorName }}</section>
                    <section class="text-12">
                        <span>{{ data.applicantUserName }}</span>
                        <a-divider type="vertical"/>
                        <span>{{ data.vendorContactName }}</span>
                        <a-divider type="vertical"/>
                        <span>{{ data.vendorContactPhone }}</span>
                    </section>
                </template>

                <template #carInfo="val, data">
                    <section class="text-16 font-bold mb-4">{{ data.vehicleLicenceNum }}</section>
                    <section class="ss-break-all">
                        {{ data | getVehicleTypeName }}
                    </section>
                </template>
                <section slot="status" slot-scope="val, data">
                    <section v-if="!$utils.getEnumName(auditStatusEnums, data.status)">待处理</section>
                    <section v-else>
                        <section class="mb-4">已处理</section>
                        <a-button type="primary" size="small" ghost v-if="data.status === 1">已同意</a-button>
                        <a-tooltip :title="data.auditRefusedReason">
                            <a-button type="danger" size="small" ghost v-if="data.status === 2">
                                <span>已拒绝</span>
                            </a-button>
                        </a-tooltip>
                        <!--						{{ $utils.getEnumName(auditStatusEnums, data.status) || '待处理' }}-->
                    </section>
                </section>
                <template #action="val, data">
                    <section style="height: 60px" class="flex flex-col justify-center">
                        <a v-if="$permissionJudge('VehicleAuditUpdate')"
                           :class="{disabled: data.status !== 0 }"
                           href="javascript:void(0);"
                           @click="handleAudit(data)">快速处理</a>
                        <a v-if="(data.status !== 0 && data.vehicleLicenceNum)" href="javascript:void(0);"
                           @click="handlePreview(data)">车辆详情</a>
                    </section>

                </template>
            </a-table>
            <a-modal
                :title="isPreview ? '车辆详情' : `快速处理-${$utils.getEnumName(auditEntityTypeEnums, currCarData.auditEntityType)}`"
                width="1060px"
                :dialog-style="{top: '30px'}"
                :body-style="{padding: '12px 24px'}"
                v-model="showHandleModal"
            >
                <a-spin v-if="showHandleModal" :spinning="detailsLoading">
                    <a-tabs v-if="currCarData.auditEntityType === 4 && !isPreview"
                            style="margin-top: -12px;"
                            v-model="tab">
                        <a-tab-pane key="carInfo" tab="申请修改车辆信息" :forceRender="true">
                            <TravelInfo v-if="tab==='carInfo'" ref="travelInfo" :car-data="{
                                    ...(currCarData.auditEntityType === 3 && !isPreview ?
                                     currCarData.oldVehicleInfo : currCarData.newVehicleInfo)}"
                                        :base-car-data="currCarData"
                                        :oldCarData="{...currCarData.oldVehicleInfo}"
                            />
                        </a-tab-pane>
                        <a-tab-pane key="beforeInfo" tab="修改前车辆信息" :forceRender="true">
                            <TravelInfo v-if="tab==='beforeInfo'" ref="travelInfo"
                                        :base-car-data="currCarData"
                                        :car-data="{ ...currCarData.oldVehicleInfo}"/>
                        </a-tab-pane>
                    </a-tabs>
                    <section v-else style="padding-right: 8px; height: calc(100vh - 248px); overflow: auto;">
                        <TravelInfo ref="travelInfo"
                                    :base-car-data="currCarData"
                                    :car-data="{...currCarData, ...currCarData.oldVehicleInfo}"/>
                    </section>
                </a-spin>
                <template #footer>
                    <template v-if="isPreview">
                        <a-button type="primary" @click="showHandleModal = false">好的</a-button>
                    </template>
                    <template v-else>
                        <a-button type="primary" @click="confirm">同意</a-button>
                        <a-button type="danger" ghost @click="showRefuseModal = true">拒绝</a-button>
                        <a-button @click="showHandleModal = false">取消</a-button>
                    </template>
                </template>
            </a-modal>
            <a-modal
                title="填写审批不通过理由"
                v-model="showRefuseModal"
                width="666px"
                :confirm-loading="confirmLoading"
                @ok="confirmRefuse"
            >
                <a-form>
                    <a-form-item required label="审核不通过理由">
                        <a-textarea :rows="4" :max-length="500" v-model="auditRefusedReason"
                                    placeholder="请输入审核不通过理由"/>
                    </a-form-item>
                </a-form>
            </a-modal>
        </a-card>
    </a-spin>
</template>

<script>
import {
    getAuditCarList,
    getCarDetail,
    updateCar
} from '@/api/vendor'
import {tableMixins} from '@/utils/mixins'
import TravelInfo from './TravelInfo'
import _ from 'lodash'

export default {
    name: 'CarAudit',
    mixins: [tableMixins],
    props: {
        tabKey: {
            type: String,
            required: true
        }
    },
    components: {TravelInfo},
    data() {
        return {
            isExpand: false,
            loading: false,
            isHandle: false,
            isPreview: false,
            detailsLoading: false,
            confirmLoading: false,
            showHandleModal: false,
            showRefuseModal: false,
            tab: 'carInfo',
            vendorName: '',
            vehicleLicenceNum: '',
            auditRecordId: '',
            auditRefusedReason: '',
            currCarData: {
                newVehicleInfo: {},
                oldVehicleInfo: {}
            },
            columns: [
                {
                    title: '审核单号',
                    dataIndex: 'id',
                    width: 160,
                    align: 'center',
                    scopedSlots: {customRender: 'id'}
                },
                {
                    title: '申请人',
                    width: 300,
                    dataIndex: 'userInfo',
                    align: 'center',
                    scopedSlots: {customRender: 'userInfo'}
                },
                {
                    title: '车辆信息',
                    dataIndex: 'carInfo',
                    align: 'center',
                    width: 300,
                    scopedSlots: {customRender: 'carInfo'}
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    width: 160,
                    align: 'center',
                    scopedSlots: {customRender: 'status'}
                },
                {
                    title: '申请时间',
                    width: 160,
                    dataIndex: 'createTime',
                    align: 'center',
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    width: 80,
                    fixed: 'right',
                    align: 'center',
                    scopedSlots: {customRender: 'action'}
                },
            ],
            data: [],
            transmissionTypeEnums: [],
            auditStatusEnums: [],
            auditEntityTypeEnums: []
        }
    },
    watch: {
        showHandleModal(val) {
            if (!val) {
                this.isPreview = false
            }
        },
        showRefuseModal(val) {
            if (!val) {
                this.auditRefusedReason = ''
            }
        }
    },
    async created() {
        this.transmissionTypeEnums = await this.$utils.getDictList('TransmissionType')
        this.auditStatusEnums = await this.$utils.getDictList('AuditStatus')
        this.auditEntityTypeEnums = await this.$utils.getDictList('AuditEntityType')
        this.getData()
    },
    methods: {
        getData() { // 获取列表
            this.loading = true
            getAuditCarList({
                pageNo: this.pageNum,
                pageSize: this.rowsNum,
                vendorName: this.vendorName.trim(),
                isHandle: this.isHandle,
                vehicleLicenceNum: this.vehicleLicenceNum.trim(),
                auditRecordId: this.auditRecordId.trim()
            }).then((res) => {
                this.data = res.items
                this.total = res.rowCount
            }).finally(() => {
                this.loading = false
            })
        },
        carDataValue(formData) {
            formData = formData.reduce((prev, curr) => {
                return {...prev, ...curr}
            }, {})
            if (this.currCarData.auditEntityType === 4 && !this.isPreview) {
                const res = {
                    ...this.currCarData,
                    ...this.currCarData.newVehicleInfo,
                    ...formData,
                    status: 1,
                }
                res.driveLicenseImg = res.driveLicenceImg
                return res
            }
            const result = {
                ...this.currCarData,
                ...this.currCarData.oldVehicleInfo,
                ...formData,
                status: 1,
            }
            result.driveLicenseImg = result.driveLicenceImg
            return result
        },
        //sleep
        sleep(time) {
            return new Promise((resolve) => setTimeout(resolve, time))
        },
        async confirm() {
            try {
                this.tab = 'carInfo'
                this.confirmLoading = true
                await this.sleep(500)
                const travelInfoForm = await this.$refs.travelInfo.GetFormAllValidate()
                if (!travelInfoForm) {
                    this.confirmLoading = false
                    return
                }
                const send = this.carDataValue(travelInfoForm)
                delete send.fuelCapacity
                delete send.vehicleSource
                updateCar(send).then(() => {
                    this.$message.success('审批成功！')
                    this.showHandleModal = false
                    this.getData()
                }).finally(() => this.confirmLoading = false)

            } catch (e) {
                this.confirmLoading = false
                this.$message.error('请填写完整信息！')
            }

        },
        confirmRefuse() {
            const auditRefusedReason = this.auditRefusedReason.trim()
            if (!auditRefusedReason) return this.$message.warning('请输入审核不通过理由')
            this.confirmLoading = true
            updateCar({
                id: this.currCarData.id,
                status: 2,
                auditRefusedReason
            }).then(() => {
                this.$message.success('审批成功！')
                this.showRefuseModal = false
                this.showHandleModal = false
                this.getData()
            }).finally(() => this.confirmLoading = false)
        },
        handleAudit(record) {
            if (record.status !== 0) return
            this.detailsLoading = true
            getCarDetail({id: record.id}).then(data => {
                this.currCarData = this.handleInvalidField({...record, ...data})
                this.showHandleModal = true
            }).finally(() => this.detailsLoading = false)
        },
        //无效字段处理
        handleInvalidField(record) {
            const {newVehicleInfo, oldVehicleInfo} = record
            const newVehicleInfoKeys = Object.keys(newVehicleInfo)
            const oldVehicleInfoKeys = Object.keys(oldVehicleInfo)
            newVehicleInfoKeys.forEach(key => {
                if (newVehicleInfo[key] === null ||
                    newVehicleInfo[key] === undefined ||
                    newVehicleInfo[key] === 0 ||
                    newVehicleInfo[key] === '0001-01-01 00:00:00') {
                    newVehicleInfo[key] = ''
                }
            })
            oldVehicleInfoKeys.forEach(key => {
                if (oldVehicleInfo[key] === null ||
                    oldVehicleInfo[key] === undefined ||
                    oldVehicleInfo[key] === 0 ||
                    oldVehicleInfo[key] === '0001-01-01 00:00:00') {
                    oldVehicleInfo[key] = ''
                }
            })
           if(record.auditEntityType !== 4 && record.minCompensationFee === undefined ) {
               oldVehicleInfo.minCompensationFee = 1500
           }
            return record
        },


        handlePreview(record) {
            this.isPreview = true
            this.detailsLoading = true
            this.showHandleModal = true
            getCarDetail({id: record.id}).then(data => {
                this.currCarData = {
                    ...record,
                    ...data
                }
            }).finally(() => this.detailsLoading = false)
        },
        search() { // 搜索
            this.pageNum = 1
            this.getData()
        },

        reset() { // 重置
            this.isHandle = undefined
            this.vendorName = ''
            this.vehicleLicenceNum = ''
            this.auditRecordId = ''
            this.search()
        },
    }
}
</script>

<style scoped lang="less">
.ss-img {
    border: 1px solid #eee;
}

.ss-pics-box {
    min-height: 350px
}
</style>
